package com.itheima.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.itheima.common.BaseContext;
import com.itheima.common.R;
import com.itheima.domain.ShoppingCart;
import com.itheima.service.ShoppingCartService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.List;

@RestController
@RequestMapping("/shoppingCart")
@Slf4j
public class ShoppingCartController {

    @Autowired
    private ShoppingCartService shoppingCartService;

    /**
     * 查询购物车列表
     *
     * @return
     */
    @GetMapping("/list")
    public R<List> list() {

        LambdaQueryWrapper<ShoppingCart> shoppingCartlqw = new LambdaQueryWrapper<>();
        shoppingCartlqw.eq(ShoppingCart::getUserId, BaseContext.getThreadLocal());
        shoppingCartlqw.orderByDesc(ShoppingCart::getCreateTime);
        List<ShoppingCart> shoppingCartList = shoppingCartService.list(shoppingCartlqw);

        return R.success(shoppingCartList);
    }

    /**
     * 添加购物车
     * @param shoppingCart
     * @return
     */
    @PostMapping("/add")
    public R<ShoppingCart> add(@RequestBody ShoppingCart shoppingCart) {

        LambdaQueryWrapper<ShoppingCart> shoppingCartlqw = new LambdaQueryWrapper<>();
        shoppingCartlqw.eq(ShoppingCart::getUserId, BaseContext.getThreadLocal());
        shoppingCartlqw.eq(shoppingCart.getDishId() != null, ShoppingCart::getDishId, shoppingCart.getDishId());
        shoppingCartlqw.eq(shoppingCart.getSetmealId() != null, ShoppingCart::getSetmealId, shoppingCart.getSetmealId());

        ShoppingCart shoppingCartOne = shoppingCartService.getOne(shoppingCartlqw);

        if (shoppingCartOne != null) {
            shoppingCartOne.setNumber(shoppingCartOne.getNumber() + 1);
            shoppingCartService.updateById(shoppingCartOne);
        } else {
            shoppingCart.setUserId(BaseContext.getThreadLocal());
            shoppingCart.setCreateTime(LocalDateTime.now());
            shoppingCart.setNumber(1);
            shoppingCartService.save(shoppingCart);
            shoppingCartOne = shoppingCart;
        }
        return R.success(shoppingCartOne);
    }

    /**
     * 删除购物车
     * @return
     */
    @DeleteMapping("/clean")
    public R<String> deletebyid(){
        LambdaQueryWrapper<ShoppingCart> shoppingCartlqw = new LambdaQueryWrapper<>();
        shoppingCartlqw.eq(ShoppingCart::getUserId,BaseContext.getThreadLocal());
        shoppingCartService.remove(shoppingCartlqw);
        return R.success("购物车删除成功!");
    }
}
